package com.lft.freshordering.controller;

import com.lft.freshordering.entity.Audit;
import com.lft.freshordering.entity.User;
import com.lft.freshordering.entity.VO.WeiXiVo;
import com.lft.freshordering.response.R;
import com.lft.freshordering.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @GetMapping("/getOpenId")
    public R getOpenId(String code) {
        Audit audit1 = null;

// 创建一个新的WeiXiVo对象
        WeiXiVo weiXiVo = new WeiXiVo();
        // 调用loginService的getOpenId方法，传入code参数，获取用户的OpenID
        String openId = loginService.getOpenId(code);
        // 打印获取到的OpenID，仅用于调试
        System.out.println("获取到的OpenID: " + openId);
        // 根据OpenID查询对应的用户信息
        User user = loginService.selectOpenid(openId);
        System.out.println("+++++++++++++++++++++牛逼" + user);
        if (user == null) {
            loginService.insertUser(openId);
            user = loginService.selectOpenid(openId);
        }

        audit1 = loginService.selectAuditStatus(user.getId());

        System.out.println(audit1);



        // 检查OpenID是否为空
        if (openId == null) {
            // 如果OpenID为空，返回一个失败响应，而不是尝试插入null值
            return R.error(400, "获取OpenID失败");
        }


            // 设置WeiXiVo对象的OpenID属性
            weiXiVo.setOpenid(openId);

            // 设置WeiXiVo对象的用户ID属性
            weiXiVo.setUid(user.getId());

            // 打印WeiXiVo对象的OpenID和用户ID，仅用于调试
            System.out.println("WeiXiVo对象的OpenID和用户ID和审核状态: " + weiXiVo.getOpenid() + ", " + weiXiVo.getUid()+","+weiXiVo.getReviewStatus());


        if (audit1 != null) {
            weiXiVo.setReviewStatus(audit1.getReviewStatus());
        } else {
            // 处理 audit1 为 null 的情况，例如设置默认审核状态
//            weiXiVo.setReviewStatus("未审核");
        }

        // 返回一个成功响应，包含WeiXiVo对象
        return R.success(weiXiVo);
    }
}
